package logic

import (
	"context"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"time"
	"xialou_platform/services/wallet/model"
	"xialou_platform/services/wallet/rpc/internal/svc"
	"xialou_platform/services/wallet/rpc/walletClient"

	"github.com/zeromicro/go-zero/core/logx"
)

type WalletIncomeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWalletIncomeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WalletIncomeLogic {
	return &WalletIncomeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// WalletIncome 钱包收入
func (l *WalletIncomeLogic) WalletIncome(in *walletClient.WalletIncomeReq) (*walletClient.EmptyBody, error) {
	nowTime := time.Now()
	if err := l.svcCtx.WalletModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// SourceType 关联类型（1.代理商 2.商家）; SourceId 关联ID
		// 查询到商家钱包
		walletInfo, err := l.svcCtx.WalletModel.FindOneBySourceId(l.ctx, in.SourceId)
		if err != nil && !errors.Is(err, model.ErrNotFound) {
			logx.Error("WalletIncome->FindOneBySourceId err : %v , in : %s", err, in.String())
			return err
		}
		if walletInfo != nil {
			// 查询是否已经有入账记录了
			count, err2 := l.svcCtx.WalletLogModel.CheckBillCountByBusiness(l.ctx, in.SourceId,
				in.OrderId, 2, 1)
			if err2 != nil {
				logx.Error("WalletIncome->CheckBillCountByBusiness err : %v", err2)
			}
			if count > 0 {
				logx.Errorf("WalletIncome->CheckBillCountByBusiness err : %v", "数据库中已有该入账记录")
				return nil
			}
		}

		if walletInfo == nil {
			walletInfo = &model.Wallet{
				Id:         l.svcCtx.Flake.Generate().Int64(),
				SourceType: in.SourceType,
				SourceId:   in.SourceId,
				Balance:    in.Amount,
				Status:     1,
				CreateTime: nowTime,
				UpdateTime: nowTime,
			}
			_, err = l.svcCtx.WalletModel.TransInsert(l.ctx, session, walletInfo)
			if err != nil {
				logx.Error("WalletIncome->TransInsert err : %v , in : %s", err, in.String())
				return err
			}
		} else {
			walletInfo.Balance += in.Amount
			walletInfo.UpdateTime = nowTime
			err = l.svcCtx.WalletModel.TransUpdate(l.ctx, session, walletInfo)
			if err != nil {
				logx.Error("WalletIncome->TransUpdate err : %v , in : %s", err, in.String())
				return err
			}
		}
		// 添加入账记录
		_, err = l.svcCtx.WalletLogModel.Insert(l.ctx, &model.WalletLog{
			Id:          l.svcCtx.Flake.Generate().Int64(),
			WalletId:    walletInfo.Id,
			SourceId:    walletInfo.SourceId,
			Type:        1,
			OrderId:     in.OrderId,
			Description: in.Description,
			Amount:      in.Amount,
			Balance:     walletInfo.Balance,
			CreateTime:  nowTime,
			UpdateTime:  nowTime,
			Business:    in.Business,
		})
		if err != nil {
			return err
		}
		return nil
	}); err != nil {
		return nil, err
	}

	return &walletClient.EmptyBody{}, nil
}
